<template>
	<div class="script-box">
		<el-table :data="userScripts" style="width: 100%; margin-top: 10px;">
			<el-table-column property="scriptId" label="脚本ID" align="center"></el-table-column>
			<el-table-column property="scriptName" label="脚本名称" align="center"></el-table-column>
			<el-table-column property="scriptContent" label="脚本介绍" align="center"></el-table-column>
			<el-table-column property="userName" label="作者名" align="center"></el-table-column>
			<el-table-column property="scriptStatus" label="脚本状态" align="center"></el-table-column>
			<el-table-column label="操作" align="center">
				<template #default="scope">
					<el-button link type="primary" size="small" @click="handleAdd(scope.row)">
						<el-icon>
							<EditPen />
						</el-icon> 导入
					</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import axios from 'axios';
	import { ElMessage, ElMessageBox } from 'element-plus';
	
	const emits = defineEmits(['refreshEvent'])

	const userScripts = ref([]);
	const user_name = ref(localStorage.getItem('user_name')); // 获取当前登录用户的用户名
	const getUserScripts = async () => {
		try {
			const response = await axios.get('/api/script/script/list');
			if (response.data.code === 200) {
				if (Array.isArray(response.data.data)) {
					userScripts.value = response.data.data.filter(script =>
						script.userName === user_name.value && script.scriptStatus === 0
					) || [];
				} else {
					console.error('Response data is not an array:', response.data.data);
				}
			} else {
				userScripts.value = [];
				ElMessage({
					message: '获取脚本失败，请重试',
					type: 'error'
				});
			}
		} catch (error) {
			console.error('Error fetching scripts:', error);
			ElMessage({
				message: '网络错误',
				type: 'error'
			});
		}
	};

	const handleAdd = async (row) => {
		ElMessageBox.confirm(
			'确认要导入选中的脚本吗?',
			'提示信息', {
				confirmButtonText: '是',
				cancelButtonText: '否',
				type: 'warning',
			}
		).then(async () => {
			try {
				// 创建一个更新的脚本对象
				const updatedScript = {
					...row,
					scriptStatus: 1 // 将脚本状态设置为1
				};

				// 调用更新脚本状态的 API
				const response = await axios.put('/api/script/script/edit', updatedScript);

				if (response.data.code === 200) {
					ElMessage({
						message: '导入成功',
						type: 'success'
					});
					getUserScripts(); // 刷新数据
					emits('refreshEvent')
				} else {
					ElMessage({
						message: '导入失败',
						type: 'error'
					});
				}
			} catch (error) {
				console.error('Error updating script status:', error);
				ElMessage({
					message: '网络错误',
					type: 'error'
				});
			}
		}).catch(() => {
			console.log('用户取消了导入脚本的操作');
		});
	};

	// 调用获取脚本的函数
	getUserScripts();

	// 组件挂载后获取脚本数据
	onMounted(() => {
		getUserScripts();
	});
</script>

<style scoped>
	.script-box {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
	}
</style>